<?php

namespace util;

use \Redis;


/*
 * Redis Helper - extending Redis to use custom methods
 *
 * @author Kevin - xuhuahai@dangdang.com
 * @version 1.0
 * @date Apr 18, 2015
 */
class Cache extends Redis {
	
	public function __construct (){
	  parent::__destruct();
	}
	
	public function __destruct(){
	  parent::__destruct();
	  parent::close();
	}
	
	/**
	 *
	 * @var array Array of saved caches for reusing
	 */
	protected static $instances = array ();
	
	/**
	 * 根据缓存名获取缓存对象
	 * @param unknown $name
	 * @return Ambigous <NULL, multitype:, \Redis>
	 */
	public static function getCacheByName($name='mobile') {
		global $global_cache_config;
		soa_debug ( 'getCacheByName : ' . $name . '=' . var_export ( $global_cache_config [$name], TRUE ) );
		return Cache::getCacheByConfig ( $global_cache_config [$name] );
	}
	
	/**
	 * 根据配置获取缓存对象
	 * @param string $group
	 * @return NULL|multitype:|\Redis
	 */
	public static function getCacheByConfig($group = false) {
		if (! $group) {
			return NULL;
		}
		
		// Group information
		$host = $group ['host'];
		$port = $group ['port'];
		
		// ID for database based on the group information
		$id = "$host.$port";
		
		// Checking if the same
		//if (isset ( self::$instances [$id] )) {
		//	return self::$instances [$id];
		//}
		
		try {
			$instance = new Cache ();
			//$instance->pconnect ( $host, $port, 3 );
			$instance->connect ( $host, $port, 3 );
			//self::$instances [$id] = $instance;
			return $instance;
		} catch ( PDOException $e ) {
			soa_error ( "getCacheByConfig error" );
		}
	}
	
	/**
	 * 键值预处理
	 * @param unknown $key
	 * @return string
	 */
	public function prepareKey($key) {
		// if key's length is too long
		if (strlen ( $key ) > 200) {
			$key = md5 ( $key );
		}
		return $key;
	}
	
	/**
	 * 设置值
	 * @param unknown $key
	 * @param unknown $value
	 * @param number $expiration_of_seconds
	 */
	public function setValue($key, $value, $expiration_of_seconds = 300) {
		$key = prepareKey ( $key );
		$value = serialize ( $value );
		$value = gzdeflate ( $value );
		$this->setex ( $key, $expiration_of_seconds, $value );
	}
	
	/**
	 * 获取值
	 * @param unknown $key
	 * @return boolean|mixed
	 */
	public function getValue($key) {
		$key = prepareKey ( $key );
		$value = $this->get ( $key );
		if ($value == false)
			return false;
		$value = gzinflate ( $value );
		$value = unserialize ( $value );
		return $value;
	}
	
	/**
	 * 删除键值
	 * @param unknown $key
	 * @return unknown
	 */
	public function deleteValue($key) {
		$key = prepareKey ( $key );
		$value = $this->delete ( $key );
		return $value;
	}
	
	/**
	 * 增加键值(已存在就放弃)
	 * @param unknown $key
	 * @param unknown $value
	 * @param number $expiration_of_seconds
	 * @return unknown
	 */
	public function addValue($key, $value, $expiration_of_seconds = 5) {
		$key = prepareKey ( $key );
		$rs = $this->setnx ( $key, $value );
		if ($rs) {
			$this->expire ( $key, $expiration_of_seconds );
		}
		return $rs;
	}
	
}

?>
